package cn.q3c.parse.impl.huihui;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.text.SimpleDateFormat;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import cn.keyvalue.ccf.common.object.DetailPage;
import cn.keyvalue.ccf.common.object.Hyperlink;
import cn.keyvalue.ccf.common.object.Image;
import cn.keyvalue.ccf.common.util.ObjectUtils;
import cn.q3c.parse.base.BaseParse;

/**
 * 慧慧页面解析
 * @author wangxinning
 *
 */
public class HuihuiIndexParseImpl implements BaseParse {

	private static final Logger logger = Logger
			.getLogger(HuihuiIndexParseImpl.class);

	public Object parse(String url, File file, String abouturl, File aboutFile) {

		try {
			Document doc = Jsoup.parse(FileUtils.readFileToString(file));
			doc.setBaseUri(url);

			// 标准元素获取
			String title = doc.title();
			String description = doc.select("meta[name=description]").attr(
					"content");
			String keywords = doc.select("meta[name=keywords]").attr("content");
			DetailPage page = new DetailPage();
			page.setUrl(url);
			page.setTitle(StringUtils.trimToEmpty(title));
			page.setDescription(StringUtils.trimToEmpty(description));
			page.setKeywords(StringUtils.trimToEmpty(keywords));

//			// 页面导航
//			List<Hyperlink> crumbs = new ArrayList<Hyperlink>();
//			Elements elements = doc.select("div[class=crumbBox]").select("a");
//			for (int i = 0; i < elements.size(); i++) {
//				Hyperlink link = new Hyperlink();
//				link.setName(elements.get(i).text());
//				link.setTitle(elements.get(i).attr("title"));
//				link.setUrl(elements.get(i).attr("abs:href"));
//				crumbs.add(link);
//			}
//			if (!crumbs.isEmpty()) {
//				page.setCrumbs(crumbs);
//			}

			// 分类
			List<Hyperlink> types = new ArrayList<Hyperlink>();
			Elements tagelements = doc.select("a[class=hico-doc hico-cagegory js-log]");
			for (int i = 0; i < tagelements.size(); i++) {
				Hyperlink link = new Hyperlink();
				link.setName(tagelements.get(i).text());
				link.setTitle(tagelements.get(i).attr("title"));
				link.setUrl(tagelements.get(i).attr("abs:href"));
				types.add(link);
			}
			if (!types.isEmpty()) {
				page.setTypes(types);
			}

			// 内容标题
			String contenttitle = StringUtils.trimToEmpty(doc.select("h1").text());
			String subcontenttitle = StringUtils.trimToEmpty(doc.select("h4").text());
			page.setBodytitle(contenttitle
					+ (StringUtils.isNotBlank(subcontenttitle) ? "<!--b-->"
							+ subcontenttitle + "<!--/b-->" : ""));

			// 发表时间
			String dateTime = StringUtils.trimToEmpty(doc.select("span[class=hico-doc hico-date]").text());
			if (StringUtils.isNotBlank(dateTime)) {				
				
				if( StringUtils.contains(dateTime, "小时") )
				{
					String num = StringUtils.substringBefore(dateTime, "小时");
					page.setDatetime(DateUtils.addHours(new Date(file.lastModified()), 0-NumberUtils.toInt(num)));
				}
				else if( StringUtils.contains(dateTime, "分钟") )
				{
					String num = StringUtils.substringBefore(dateTime, "分钟");
					page.setDatetime(DateUtils.addMinutes(new Date(file.lastModified()), 0-NumberUtils.toInt(num)));
				}
				else
				{
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
					page.setDatetime(sdf.parse(dateTime));
				}
			}

			// 内容，遇到p填入换行标记
			Elements bodyElements = doc.select("div[class=editer-main-content]").select("p");			
			String bodyStr = "";
			// 内容中的图片
			for (int i = 0; i < bodyElements.size(); i++) {
				String tempLine = bodyElements.get(i).text();
				bodyStr += "<!--b-->" + tempLine + "<!--/b-->";
			}
			page.setBody(bodyStr);
			
			Elements imageElements = doc.select("div[class=editer-main-content]").select("img");
			if( imageElements != null && !imageElements.isEmpty() )
			{
				List<Image> images = new ArrayList<Image>();
				for (int i = 0; i < imageElements.size(); i++) {
					Image img = new Image();
					img.setSrc(imageElements.get(i).attr("abs:src"));
					img.setAlt(imageElements.get(i).attr("alt"));// alt
					img.setWidth(NumberUtils.toInt(imageElements.get(i).attr(
							"width")));
					img.setHeight(NumberUtils.toInt(imageElements.get(i)
							.attr("height")));
					images.add(img);
				}
				
				if (!images.isEmpty()) {
					page.setImages(images);
				}
			}

			// 直达链接
			Hyperlink jumpLink = new Hyperlink();
			Elements zhidaElements = doc.select("h1")
					.select("a");
			if (zhidaElements != null && !zhidaElements.isEmpty()) {
				jumpLink.setUrl(zhidaElements.get(0).attr("abs:href"));
				page.setNextHyperlink(jumpLink);
			}

//			// 标签
//			List<Hyperlink> tags = new ArrayList<Hyperlink>();
//			tagelements = doc.select("span[class=classified]").select("a");
//			for (int i = 0; i < tagelements.size(); i++) {
//				Hyperlink link = new Hyperlink();
//				link.setName(tagelements.get(i).text());
//				link.setTitle(tagelements.get(i).attr("title"));
//				link.setUrl(tagelements.get(i).attr("abs:href"));
//				tags.add(link);
//			}
//			// 标签尾部加入商城信息
//			Hyperlink link = new Hyperlink();
//			String shopname = doc.select("span[class=from_val]").text();
//			link.setName(shopname);
//			if (StringUtils.isNotBlank(shopname)) {
//				link.setName(shopname);
//				tags.add(link);
//			}
//			if (!tags.isEmpty()) {
//				page.setTags(tags);
//			}

			
			// 简介和小图片解析，从相关内容中寻找++++++++++++
			Document aboutdoc = Jsoup.parse( StringUtils.replace( FileUtils.readFileToString(aboutFile), "\"perContentBox \"", "\"perContentBox\"" ));
			aboutdoc.setBaseUri(abouturl);
			Elements elements = doc.select("div[class=perContentBox]");
			for (int i = 0; i < elements.size(); i++) {
				
				Element element = elements.get(i);
				if( StringUtils.contains(element.html(),url ) )
				{
					//添加小图片的
					Elements imgElements = element.select("img");
					if( imgElements != null && !imgElements.isEmpty() )
					{
						Image img = new Image();
						img.setSrc(imgElements.get(0).attr("src"));
						img.setAlt(imgElements.get(0).attr("alt"));
						page.addSmallImage(img);
						break;
					}
					
					//添加简介
					//Elements summaryElements = element.select("img");
				}
			}
			
			
			//返回内容打印
			logger.debug("page:" + page);
			
			//一个分类都没有的是不需要的数据，特质惠惠网
			if (ObjectUtils.isEmptyList(page.getCrumbs())
					&& ObjectUtils.isEmptyList(page.getTags())
					&& ObjectUtils.isEmptyList(page.getTypes())) {
				return null;
			}

			return page;

		} catch (Exception e) {

			logger.error("解析慧慧网详情页异常", e);
		}

		return null;
	}
	
	
	
	public static void main( String[] args ) throws MalformedURLException, IOException
	{
		HuihuiIndexParseImpl huihuiIndexParseImpl = new HuihuiIndexParseImpl();
		String url = "http://www.huihui.cn/deals/12498826";
		File file = new File(SystemUtils.getJavaIoTmpDir() + File.separator + "aaa.ttt");
		FileUtils.copyURLToFile(new URL(url), file);
		
		//System.out.println( huihuiIndexParseImpl.parse(url, file) );
		
	}
}